import React from 'react';
import { connect } from 'dva';
import _ from 'lodash';
import { Link, routerRedux } from 'dva/router';
import { Table, message, Icon } from 'antd';
import { getCol } from '../task/col';

const styles = require('../app.less');

class ExaminePack extends React.Component {
  constructor(p) {
    super(p);
    this.getPackOp = this.getPackOp.bind(this);
    this.startExamine = this.startExamine.bind(this);
    this.state = {
      loadingId: null,
    };
  }

  componentDidMount() {
    this.queryData();
  }


  // 根据当前包的状态来决定按钮的文字
  // 如果一个包正在被处理，那么就什么也不能做
  // 如果一个包不在处理，那么就能处理这个包
  // 为了避免两个人同时刷到同一个包
  // 需要做两层的处理：
  // 第一个需要每隔1s刷新数据包
  // 第二个是在请求处理这个包的时候需要先拉取数据，然后判断这个包是否已经被人占有，占有就退出
  getPackOp() {
    const { loading } = this.props;
    const { loadingId } = this.state;
    return [{
      title: '操作',
      key: 'op',
      render: (text, record) => {
        if (record.examineState === 'doing' || !record.examineState) {
          return (
            <div>
              {
                (loading.effects['examine/startExamine'] && loadingId === record.id)
                && <Icon style={{ color: 'blue' }} type="loading" />
              }
              <a onClick={this.startExamine(record)}>开始审核</a>
            </div>
          );
        } else if (record.examineState === 'close') {
          return (
            <div>
              <Link>查看</Link>
            </div>
          );
        }
      },
    }];
  }

  startExamine(pack) {
    return () => {
      const { dispatch } = this.props;
      // 设置加载id
      this.setState({
        loadingId: pack.id,
      });

      dispatch({
        type: 'examine/startExamine',
        payload: {
          value: pack,
          onEnd: (err) => {
            if (err) {
              return message.error(err);
            }
            dispatch(routerRedux.push({
              pathname: 'examineRecord',
              query: {
                packId: pack.id,
              },
            }));
          },
        },
      });
    };
  }

  queryData() {
    const id = _.get(this, 'props.location.query.taskId');
    const { dispatch } = this.props;
    // 查询包
    dispatch({
      type: 'record/queryPackage',
      payload: {
        id,
      },
    });
  }

  render() {
    const {
      packages, packageKeys,
    } = this.props.record;
    const { loading } = this.props;

    return (
      <div className={styles.container}>
        <h2>包列表：</h2>
        <Table
          columns={_.unionBy(getCol(packageKeys), this.getPackOp(), 'key')}
          dataSource={packages}
          loading={loading.effects['record/queryPackage']}
          rowKey="id"
        />
      </div>
    );
  }
}

export default connect(state => state)(ExaminePack);
